package com.gywj.race.wxPub;

import com.alibaba.fastjson.JSONObject;
import com.gywj.race.config.exception.BaseException;
import com.gywj.race.util.HttpClient;
import com.gywj.race.wxPay.MyWxPayConfig;
import com.gywj.race.wxPay.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class WxPubUtil {
    private static Logger log = LoggerFactory.getLogger(WxPubUtil.class);

    //jsapi_ticket
    private final static String JSAPI_TICKET = "jsapi";

    public static String getBaseUrl(String redirectUrl) {
        try {
            MyWxPayConfig myWxConfig = new MyWxPayConfig();


            String accessTokenUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE&connect_redirect=1#wechat_redirect"
                    .replace("APPID", myWxConfig.getAppID())
                    .replace("REDIRECT_URI", URLEncoder.encode(redirectUrl))
                    .replace("SCOPE", "snsapi_userinfo")
                    .replace("STATE", "1");
            System.out.println(accessTokenUrl);
            return accessTokenUrl;

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }

    }


    private static String sha1(String src) {
        try {
            char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            MessageDigest md = MessageDigest.getInstance("sha1");
            byte[] digest = md.digest(src.getBytes());
            StringBuffer sb = new StringBuffer();
            for (byte b : digest) {
                sb.append(chars[(b >> 4) & 15]);
                sb.append(chars[b & 15]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject getOpenIdByCode(String code) {
        try {
            log.info("code===========" + code);
            MyWxPayConfig myWxConfig = new MyWxPayConfig();
            String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"
                    .replace("APPID", myWxConfig.getAppID())
                    .replace("CODE", code)
                    .replace("SECRET", myWxConfig.getSecret());
            HttpClient httpClient = new HttpClient(accessTokenUrl);
            httpClient.setHttps(true);
            httpClient.get();
            String content = httpClient.getContent();
            log.info("jsonObject===========" + content);
            JSONObject jsonObject = JSONObject.parseObject(content);
            if (jsonObject.containsKey("errcode")) {
                throw new BaseException("errcode" + ":" + jsonObject.getString("errcode" + "," + "errmsg" + ":" + jsonObject.getString("errmsg")));
            }
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    public static JSONObject getAccessToken() {
        try {
            MyWxPayConfig myWxConfig = new MyWxPayConfig();
            String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"
                    .replace("APPID", myWxConfig.getAppID())
                    .replace("APPSECRET", myWxConfig.getSecret());
            HttpClient httpClient = new HttpClient(accessTokenUrl);
            httpClient.setHttps(true);
            httpClient.get();
            String content = httpClient.getContent();
            log.info("jsonObject===========" + content);
            return JSONObject.parseObject(content);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    public static JSONObject getTicket(String accessToken) {
        try {
            String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"
                    .replace("ACCESS_TOKEN", accessToken);
            HttpClient httpClient = new HttpClient(ticketUrl);
            httpClient.setHttps(true);
            httpClient.get();
            String content = httpClient.getContent();
            log.info("jsonObject===========" + content);
            return JSONObject.parseObject(content);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }


    public static String getSignature(String ticket, String url) {
        String nonce_str = WXPayUtil.generateNonceStr();//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
        //获取url
        //将参数排序并拼接字符串
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        //将字符串进行sha1加密
        return sha1(str);
    }
}
